import React, { useState, useRef } from "react";
import { NextPage } from "next";
import {
  Card,
  List,
  message,
  Spin,
  Upload,
  Icon,
  Drawer,
  Row,
  Col,
  Button,
  Popconfirm,
  Alert
} from "antd";
import Viewer from "viewerjs";

import { SPTDataTable } from "@/components/SPTDataTable";
import { AdminLayout } from "@/layout";
import { FileApi } from "@/api/file";
import style from "./index.module.scss";
import dayjs from "dayjs";
import { useSettings } from "@/hooks/settings";
import Link from "next/link";
const copy = value => {
  let textarea: any = document.createElement("textarea");
  textarea.id = "t";
  textarea.style.height = 0;
  document.body.appendChild(textarea);
  textarea.value = value;
  let selector: any = document.querySelector("#t");
  selector.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  message.success("链接已复制到剪切板");
};
const DescriptionItem = ({ title, content }) => {
  return (
    <div className={style.decItem}>
      <p className={style.title}>{title}</p>
      <div className={style.content}>{content}</div>
    </div>
  );
};
let viewer;
const File: NextPage = () => {
  const previewRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [files, setFiles] = useState([]);
  const [currentFile, setCurrentFile] = useState<IFile>(null);
  // 获取所有文件数据
  const getFiles = async params => {
    return FileApi.getFiles(params)
      .then(res => {
        setFiles(res[0]);
        setLoading(false);
        return res;
      })
      .catch(err => {});
  };
  // 自定义上传方法
  const upload = data => {
    const file = data.file;
    const size = file.size;
    if (size / 1024 / 1024 > 50) {
      return message.warn("文件最大不能超过50M");
    }
    setLoading(true);
    FileApi.upload(file).then(res => {
      setLoading(false);
      message.success("文件上传成功");
      getFiles({});
    });
  };
  // 删除文件
  const deleteFile = () => {
    const { id } = currentFile;
    FileApi.deleteFile(id).then(res => {
      message.success("文件删除成功");
      setVisible(false);
      getFiles({});
    });
  };
  const preview = () => {};
  const settings = useSettings();
  const isOSS =
    settings?.ossAccessKeyId &&
    settings?.ossAccessKeySecret &&
    settings?.ossBucket &&
    settings?.ossRegion;
  return (
    <AdminLayout>
      {isOSS ? (
        <Spin spinning={loading} tip="文件上传中">
          <Upload.Dragger
            style={{ marginBottom: 20 }}
            customRequest={upload}
            showUploadList={false}
          >
            <p className="ant-upload-icon">
              <Icon type="inbox" />
            </p>
            <p className="ant-upload-title">将文件拖拽到此处上传</p>
            <p className="ant-upload-text">必须配置正确的阿里云OSS</p>
          </Upload.Dragger>
        </Spin>
      ) : (
        <Alert
          style={{ marginBottom: 15 }}
          type="warning"
          message={
            <Link href="/setting?type=oss">
              <a style={{ color: "#333" }}>
                阿里云OSS配置信息不完整，点我去配置
              </a>
            </Link>
          }
        />
      )}

      <SPTDataTable
        searchFields={[
          {
            label: "文件名",
            msg: "请输入文件名",
            field: "originalname"
          },
          {
            label: "文件类型",
            field: "type",
            msg: "请输入文件类型"
          }
        ]}
        columns={[]}
        data={files}
        defaultTotal={0}
        onSearch={getFiles}
        //自定义渲染每个 List Item
        customRender={data => {
          return (
            <List
              grid={{ gutter: 16, sm: 4 }}
              dataSource={files}
              renderItem={(file: IFile) => (
                <List.Item
                  onClick={() => {
                    setVisible(true);
                    setCurrentFile(file);
                  }}
                >
                  <Card hoverable>
                    <div className={style.preview} onClick={preview}>
                      <img src={file.url} alt={file.originalname} />
                    </div>
                    <Card.Meta
                      title={file.originalname}
                      description={
                        "上传于：" +
                        dayjs(file.createAt).format("YYYY-MM-DD-hh-mm")
                      }
                    />
                  </Card>
                </List.Item>
              )}
            />
          );
        }}
      />
      <Drawer
        title={"文件信息"}
        placement="left"
        width={600}
        closable={true}
        onClose={() => setVisible(false)}
        visible={visible}
        bodyStyle={{ marginBottom: 55 }}
      >
        <div
          ref={previewRef}
          className={style.previewContainer}
          style={{ marginBottom: 15 }}
          onClick={() => {
            if (!viewer) {
              viewer = new Viewer(previewRef.current, { inline: false });
            } else {
              viewer.update();
            }
          }}
        >
          <img
            width="100%"
            src={currentFile?.url || null}
            alt={currentFile?.originalname || null}
          />
        </div>
        <Row gutter={20}>
          <Col span={24}>
            <DescriptionItem
              title={"文件名"}
              content={currentFile?.originalname || null}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={24}>
            <DescriptionItem
              title={"存储路径"}
              content={currentFile?.filename || null}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={12}>
            <DescriptionItem
              title={"文件大小"}
              content={
                currentFile?.size / 1024 / 1024 < 1
                  ? (currentFile?.size / 1024).toFixed(2) + "KB"
                  : (currentFile?.size / 1024 / 1024).toFixed(2) + "MB"
              }
            />
          </Col>
          <Col span={12}>
            <DescriptionItem
              title={"文件类型"}
              content={currentFile?.type || null}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={24}>
            <DescriptionItem
              title={"访问链接"}
              content={
                <p onClick={() => copy(currentFile?.url)}>
                  {currentFile?.url || null}
                  <span
                    style={{
                      paddingLeft: 15,
                      color: "skyblue",
                      cursor: "pointer"
                    }}
                  >
                    复制
                  </span>
                </p>
              }
            />
          </Col>
        </Row>
        <div
          style={{
            width: "100%",
            padding: "15px",
            borderTop: "solid 1px #ccc",
            position: "absolute",
            bottom: 0,
            backgroundColor: "#fff"
          }}
        >
          <Button style={{ marginRight: 15 }}>关闭</Button>
          <Popconfirm
            title="确定要删除这个文件吗"
            okText="确定"
            cancelText="取消"
            onConfirm={deleteFile}
          >
            <Button type="danger">删除</Button>
          </Popconfirm>
        </div>
      </Drawer>
    </AdminLayout>
  );
};

export default File;
